//app.js
App({
  onLaunch: function () {
    this.globalData.myDevice = wx.getSystemInfoSync()
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 读取Token
    try{
      var token = wx.getStorageSync('baidu_api_token')
      if(!token){
        this.getBaiduApiToken()
      }
      else{
        this.globalData.token = token
      }
    }catch(e){
      console.log(e)
      this.getBaiduApiToken()
    }
    //console.log(this.globalData.myDevice)
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }
    else{
      //调用登录接口
      wx.login({
        success: function () { 
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },

  /**
   * 获取百度API Token
   */
  getBaiduApiToken:function(){
    //https://aip.baidubce.com
    var self = this
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token', 
      data: {
        grant_type: 'client_credentials',
        client_id: 'wu6fk7Uog70xzX2BSrou6juf',
        client_secret: 'pUS7sZLos3DTDZ4PUqXUC6VdgF3dH3ZZ'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        var data = res.data
        console.log(data)
        if(! data.error){
           var token = data.access_token
           try{
            wx.setStorageSync("baidu_api_token", token)
           }catch(e){
             console.log(e)
           }
           
           self.globalData.token = token
           pages = self.globalData.pages
           for(var k in pages){
              if(pages[k].onInitBaiduApi){
                pages[k].onInitBaiduApi({
                  token: token
                })
              }
           }
        }
      }
    })
  },

  globalData:{
    pages:[], //面页实例
    userInfo:null,
    serverURL:'http://rapapi.org/mockjsdata/20680/',
    myDevice:null,
    imgUrl:[],
    token: false
  }
})